package com.alan.base.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class TitleListAdapter<VT extends View, VI extends View, DT, DI> extends RecyclerView.Adapter<CommonViewHolder> {

    public static final int VIEW_TYPE_TITLE = 0;
    public static final int VIEW_TYPE_ITEM = 1;

    private final Context mContext;
    private final List<Object> list;
    private final List<Integer> titleList = new ArrayList<>();
    private final TitleView<VT, VI, DT, DI> titleView;
    private final Class<DT> dtClass;

    public TitleListAdapter(Context context, @NonNull TitleView<VT, VI, DT, DI> titleView, List<Object> list, Class<DT> dtClass) {
        this.mContext = context;
        this.list = new ArrayList<>();
        this.list.addAll(list);
        this.titleView = titleView;
        this.dtClass = dtClass;
        initTitleList();
    }

    @NonNull
    @Override
    public CommonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        CommonViewHolder view = null;
        switch (viewType) {
            case VIEW_TYPE_TITLE:
                view = new CommonViewHolder(titleView.createTitleView(mContext));
                break;
            case VIEW_TYPE_ITEM:
                view = new CommonViewHolder(titleView.createItemView(mContext));
                break;
            default:
                view = new CommonViewHolder(new View(mContext));
        }
        return view;
    }

    @Override
    public void onBindViewHolder(@NonNull CommonViewHolder holder, int position) {
        View itemView = holder.itemView;
        int itemViewType = getItemViewType(position);
        if(itemViewType==VIEW_TYPE_TITLE){
            titleView.setTitle((VT) itemView,position, (DT) list.get(position));
        } else if (itemViewType == VIEW_TYPE_ITEM) {
            titleView.setItem((VI) itemView,position, (DI) list.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public int getItemViewType(int position) {
        return titleList.contains(position) ? VIEW_TYPE_TITLE : VIEW_TYPE_ITEM;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void refresh(List<Object> list) {
        this.list.clear();
        titleList.clear();
        this.list.addAll(list);
        initTitleList();
        notifyDataSetChanged();
    }

    private void initTitleList(){
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if (o.getClass().getSimpleName().equals(dtClass.getSimpleName())) {
                titleList.add(i);
            }
        }
    }
}
